package com.tseng.examples;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.content.Intent;

public class LoginExample extends Activity {
	// Declare our Views, so we can access them later
	private EditText etUsername;
	private EditText etPassword;
	private Button btnLogin;
	private Button btnCancel;
	private TextView lblResult;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set Activity Layout
        setContentView(R.layout.main);
        
        // Get the EditText and Button References
        etUsername = (EditText)findViewById(R.id.username);
        etPassword = (EditText)findViewById(R.id.password);
        btnLogin = (Button)findViewById(R.id.login_button);
        btnCancel = (Button)findViewById(R.id.cancel_button);
        lblResult = (TextView)findViewById(R.id.result);

        // Set Click Listener
        btnLogin.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// Check Login
				String username = etUsername.getText().toString();
				String password = etPassword.getText().toString();
				JSONArray jsonArray;
				//ConnectClass accountInformation; //does not work yet...will refactor later
				jsonArray=login(username, password);
				if(jsonArray!=null) //login successful
				{
					Intent i = new Intent(getApplicationContext(), MapTestActivity.class);
	                startActivity(i);
				}
				else
				{
					lblResult.setText("Login failed. Username and/or password doesn't match.");
				}
				/*
				if(username.equals("guest") && password.equals("guest")){
					Intent i = new Intent(getApplicationContext(), MapTestActivity.class);
	                startActivity(i);
				} else {
					lblResult.setText("Login failed. Username and/or password doesn't match.");
				}*/
			}
		});
        btnCancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// Close the application
				finish();
			}	
		});
    }
    final int TIMEOUT_MILLISEC =30000; //30secs

    	/*@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
    		String JSONServerObject = getJSONArray();
    		try {
    			JSONArray jsonArray = new JSONArray(JSONServerObject);
    			Log.i(ConnectClass.class.getName(),
    					"Number of entries " + jsonArray.length());
    			for (int i = 0; i < jsonArray.length(); i++) {
    				JSONObject jsonObject = jsonArray.getJSONObject(i);
    				Log.i(ConnectClass.class.getName(), jsonObject.getString("PASSWORD"));
    				/*view the page(http://www.suopensim.com/connect.php) to get an idea of what 
    				 * and how json are sent. you can catch them with position location 
    				 * similar to an array or you can blantly check for the correct text field. 
    				 *//*
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		//Toast.makeText("It works");
    		sendToServer();
    	}*/
    	public JSONArray login(String username, String password)
    	{
    		Log.i("login","Envoking the login function");
    		JSONArray jsonArray =null;
    	    try {
    	        JSONObject json = new JSONObject();
    	        json.put("Username", username);
    	        
    	        json.put("Password", password);
    	        HttpParams httpParams = new BasicHttpParams();
    	        HttpConnectionParams.setConnectionTimeout(httpParams,
    	                TIMEOUT_MILLISEC);
    	        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
    	        HttpClient client = new DefaultHttpClient(httpParams);
    	        String url = "http://www.suopensim.com/app/login.php";

    	        HttpPost request = new HttpPost(url);
    	        request.setEntity(new ByteArrayEntity(json.toString().getBytes(
    	                "UTF8")));
    	        request.setHeader("json", json.toString());
    	        HttpResponse response = client.execute(request);
    	        HttpEntity entity = response.getEntity();
    	        // If the response does not enclose an entity, there is no need
    	        Log.i("login","Done connecting to server");
    	        if (entity != null) {
    	            InputStream instream = entity.getContent();
    	            Log.i("login","in the if statement");
    	            String result = convertStreamToString(instream);
    	            try{
    	            	jsonArray = new JSONArray(result);
    	            	Log.i("Read from server", jsonArray.toString());
    	            	//return jsonArray;
    	            }
    	            catch(Throwable t){
    	            	Log.e("Login", "failed");
    	            	//jsonArray;
    	            }
    	            
    	        }
    	    } catch (Throwable t) {
    			Log.e(ConnectClass.class.getName(), "Request failed: " + t.toString());
    			//Log.i("login","connect falied");
    	    }
    		
    		return jsonArray;
    	}
    	public String getJSONArray() {
    		StringBuilder builder = new StringBuilder();
    		HttpClient client = new DefaultHttpClient();
    		
    		HttpGet httpGet = new HttpGet(
    				"http://www.suopensim.com/app/fromserver.php");
    		/*view the page to get an idea of what 
    		 * and how json are sent. you can catch them with position location 
    		 * similar to an array or you can blantly check for the correct text field. 
    		 */
    														
    		try {
    			HttpResponse response = client.execute(httpGet);
    			StatusLine statusLine = response.getStatusLine();
    			int statusCode = statusLine.getStatusCode();
    			if (statusCode == 200) {
    				HttpEntity entity = response.getEntity();
    				InputStream content = entity.getContent();
    				BufferedReader reader = new BufferedReader(
    						new InputStreamReader(content));
    				String line;
    				while ((line = reader.readLine()) != null) {
    					builder.append(line);
    				}
    			} else {
    				Log.e(ConnectClass.class.toString(), "Failed to download file");
    			}
    		} catch (ClientProtocolException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return builder.toString();
    	}
    	
    	public void sendToServer() {
    	    try {
    	        JSONObject json = new JSONObject();
    	        json.put("UserName", "test2");
    	        json.put("FullName", "1234567");
    	        HttpParams httpParams = new BasicHttpParams();
    	        HttpConnectionParams.setConnectionTimeout(httpParams,
    	                TIMEOUT_MILLISEC);
    	        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
    	        HttpClient client = new DefaultHttpClient(httpParams);
    	        String url = "http://www.suopensim.com/app/toserver.php";

    	        HttpPost request = new HttpPost(url);
    	        request.setEntity(new ByteArrayEntity(json.toString().getBytes(
    	                "UTF8")));
    	        request.setHeader("json", json.toString());
    	        HttpResponse response = client.execute(request);
    	        HttpEntity entity = response.getEntity();
    	        // If the response does not enclose an entity, there is no need
    	        if (entity != null) {
    	            InputStream instream = entity.getContent();

    	            String result = convertStreamToString(instream);
    	            Log.i("Read from server", result);
    				Log.e(ConnectClass.class.getName(),
    						this + result);
    	        }
    	    } catch (Throwable t) {
    			Log.e(ConnectClass.class.getName(), "Request failed: " + t.toString());

    	    }
    	}
        public static String convertStreamToString(InputStream is) {
    	    /*
    	   * To convert the InputStream to String we use the BufferedReader.readLine()
    	    * method. We iterate until the BufferedReader return null which means
    	    * there's no more data to read. Each line will appended to a StringBuilder
    	  * and returned as String.
    	    */
    	  BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    	    StringBuilder sb = new StringBuilder();

    	    String line = null;
    	   try {
    	     while ((line = reader.readLine()) != null) {
    	          sb.append(line + "\n");
    	     }
    	  } catch (IOException e) {
    	    e.printStackTrace();
    	 } finally {
    	     try {
    	       is.close();
    	  } catch (IOException e) {
    	      e.printStackTrace();
    	    }
    	}
    	return sb.toString();
    	}
    
}